import { $http } from '../utils/request'
import { getStorage } from '../utils/auth'

let userInfo = null
getStorage('userInfo').then(value => {
  userInfo = value
})

const actions = {
  // 获取收货地址列表
  async GetAddressList(context) {
    try {
      const addressListData = await $http(
        `/1.1/classes/address?where={"userId":"${userInfo.objectId}"}`,
        'GET',
        { isUser: true }
      )
      context.commit('GET_ADDRESS_LIST', addressListData.results)
    } catch (e) {
      console.log(e)
    }
  },
  // 添加地址
  async AddAddress(context, address) {
    try {
      const result = await $http('/1.1/classes/address', 'POST', address)
      uni.showToast({
        title: '新增收货地址成功',
        duration: 2000,
        icon: 'none',
      })
      setTimeout(() => {
        uni.navigateBack({ delta: 1 })
      }, 500)
    } catch (e) {
      console.log(e)
    }
  },
  // 修改收货地址
  async EditAddress(context, address) {
    try {
      const result = await $http(
        '/1.1/classes/address/' + address.objectId,
        'PUT',
        address
      )
      uni.showToast({
        title: '修改收货地址成功',
        duration: 2000,
        icon: 'none',
      })
      setTimeout(() => {
        uni.navigateBack({ delta: 1 })
      }, 500)
    } catch (e) {
      console.log(e)
    }
  },
  // 删除收货地址
  async DelAddress(context, id) {
    try {
      await $http('/1.1/classes/address/' + id, 'DELETE')
    } catch (e) {
      console.log(e)
    }
  },
  // 设为默认地址 isDefaultBtn是否点击默认按钮，false表示点击勾选
  async SetDefault(context, { id, isDefaultBtn }) {
    try {
      const body = {}
      isDefaultBtn && (body.isDefault = false)
      !isDefaultBtn && (body.isCheck = false)
      // 排他思想，让所有的地址都取消默认，让点击的地址为默认（是否选中也一样）
      const list = context.state.addressList.map(item => ({
        method: 'PUT',
        path: '/1.1/classes/address/' + item.objectId,
        body,
      }))
      await $http('/1.1/batch', 'POST', { requests: list })

      const params = {}
      isDefaultBtn && (params.isDefault = true)
      !isDefaultBtn && (params.isCheck = true)
      await $http('/1.1/classes/address/' + id, 'PUT', params)

      this.dispatch('address/GetAddressList')
    } catch (e) {
      console.log(e)
    }
  },
}
const state = {
  addressList: [], // 收货地址列表
}
const mutations = {
  // 初始化收货地址列表
  GET_ADDRESS_LIST(state, addressList) {
    state.addressList = addressList
  },
}

export default { namespaced: true, actions, state, mutations }
